<template>
  <div class="article-container">
    <div class="header">
      <div class="search">
        <el-input
          v-model="searchForm.title"
          placeholder="搜索文章标题"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
      <div class="actions">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增文章
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="articleList"
      border
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="title" label="标题" min-width="200" />
      <el-table-column prop="categoryId" label="分类" width="120">
        <template #default="{ row }">
          {{ getCategoryName(row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column prop="subtitle" label="副标题" width="200" />
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button-group>
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑文章' : '新增文章'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="副标题" prop="subtitle">
          <el-input v-model="form.subtitle" />
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 分类数据
const categories = [
  { id: 1, name: '中药基础' },
  { id: 2, name: '针灸推拿' },
  { id: 3, name: '养生保健' },
  { id: 4, name: '经典理论' },
  { id: 5, name: '四季养生' },
  { id: 6, name: '食疗方案' }
]

// 列表数据
const loading = ref(false)
const articleList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const selectedIds = ref([])

// 搜索表单
const searchForm = ref({
  title: '',
  categoryId: ''
})

// 编辑表单
const dialogVisible = ref(false)
const formRef = ref(null)
const form = ref({
  id: '',
  title: '',
  categoryId: '',
  subtitle: '',
  content: ''
})

const rules = {
  title: [
    { required: true, message: '请输入文章标题', trigger: 'blur' },
    { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  subtitle: [
    { required: true, message: '请输入副标题', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入文章内容', trigger: 'blur' }
  ]
}

// 获取文章列表
const fetchArticleList = async () => {
  loading.value = true
  try {
    const response = await request.get('/api/v1/medical/knowledge/page', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        categoryId: searchForm.value.categoryId || undefined,
        title: searchForm.value.title || undefined
      }
    })
    
    if (response.code === '0000') {
      articleList.value = response.data
      total.value = response.data.length
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchArticleList()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticleList()
}

// 处理选择
const handleSelectionChange = (val) => {
  selectedIds.value = val.map(item => item.id)
}

// 新增
const handleAdd = () => {
  form.value = {
    id: '',
    title: '',
    categoryId: '',
    subtitle: '',
    content: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row) => {
  try {
    const response = await request.get(`/api/v1/medical/knowledge/detail/${row.id}`)
    if (response.code === '0000') {
      form.value = {
        id: response.data.id,
        title: response.data.title,
        categoryId: row.categoryId,
        subtitle: response.data.subtitle,
        content: response.data.content
      }
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取文章详情失败:', error)
    ElMessage.error('获取文章详情失败')
  }
}

// 删除
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      type: 'warning'
    })
    
    const response = await request.delete(`/api/v1/medical/knowledge/delete/${row.id}`)
    if (response.code === '0000') {
      ElMessage.success('删除成功')
      fetchArticleList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的文章')
    return
  }
  
  try {
    await ElMessageBox.confirm('确定要删除选中的文章吗？', '提示', {
      type: 'warning'
    })
    
    const response = await request.post('/api/v1/medical/knowledge/batch/delete', selectedIds.value)
    if (response.data.code === '0000') {
      ElMessage.success('批量删除成功')
      fetchArticleList()
    } else {
      ElMessage.error('批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 保存
// const handleSave = async () => {
//   if (!formRef.value) return
  
//   try {
//     await formRef.value.validate()
//     const url = form.value.id ? 
//       '/api/v1/medical/knowledge/update' : 
//       '/api/v1/medical/knowledge/add'
    
//     const response = await request.post(url, form.value)
//     if (response.code === '0000') {
//       ElMessage.success(`${form.value.id ? '更新' : '添加'}成功`)
//       dialogVisible.value = false
//       fetchArticleList()
//     }
//   } catch (error) {
//     console.error(`${form.value.id ? '更新' : '添加'}文章失败:`, error)
//     ElMessage.error(`${form.value.id ? '更新' : '添加'}失败`)
//   }
// }
const handleSave = async () => {
    if (!formRef.value) return;

    try {
        await formRef.value.validate();
        const url = form.value.id
            ? '/api/v1/medical/knowledge/update'
            : '/api/v1/medical/knowledge/add';

        let response;
        if (form.value.id) {
            // 使用 PUT 方法更新
            response = await request.put(url, form.value);
        } else {
            // 使用 POST 方法添加
            response = await request.post(url, form.value);
        }

        if (response.code === '0000') {
            ElMessage.success(`${form.value.id ? '更新' : '添加'}成功`);
            dialogVisible.value = false;
            fetchArticleList();
        }
    } catch (error) {
        console.error(`${form.value.id ? '更新' : '添加'}文章失败:`, error);
        ElMessage.error(`${form.value.id ? '更新' : '添加'}失败`);
    }
};

// 获取分类名称
const getCategoryName = (id) => {
  const category = categories.find(item => item.id === id)
  return category ? category.name : '-'
}

onMounted(() => {
  fetchArticleList()
})
</script>

<style lang="scss" scoped>
.article-container {
  padding: 20px;
  
  .header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    
    .search {
      .el-input {
        width: 300px;
      }
    }
  }
  
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 